package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-17 14:18
 **/
public class LeetCode24 {

    /**
     * 自己写的迭代解法
     * @param head
     * @return
     */
    /*public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        //指向奇数节点
        ListNode current = head;
        ListNode newHead = head.next;
        //指向前一轮的current节点
        ListNode prev = null;
        while (current != null) {
            if (prev != null) {
                if (current.next == null) {
                    prev.next = current;
                    break;
                }
                prev.next = current.next;
            }
            //存储head节点的下下个节点
            ListNode next = current.next.next;
            current.next.next = current;
            current.next = null;
            prev = current;
            current = next;
        }
        return newHead;
    }*/

    /**
     * 看了官方的迭代解法写的代码
     * @param head
     * @return
     */
    public ListNode swapPairs(ListNode head) {
        //伪头结点
        ListNode tou = new ListNode(0,head);
        ListNode temp = tou;
        while (temp.next != null && temp.next.next != null) {
            ListNode node1 = temp.next;
            ListNode node2 = temp.next.next;
            temp.next = node2;
            //将奇数节点指向下一个技术节点
            node1.next = node2.next;
            node2.next = node1;
            temp = node1;
        }
        return tou.next;

    }
}
